window.ImageHelper = {

    mime: { 'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'bmp': 'image/bmp' },
    selectedHandler: null,
    bytesHandler: null,
    thisRef: null,
    useOriginalQuality: null,
    _this: this,

    /**
     * 在html上生成一个一模一样的img图片覆盖在顶部，用于微信的长按保存和识别
     * @param {cc.Node} spriteNode 需要生成图片进行覆盖的Sprite
     * @param {string} imageBase64 用于Html外部的Base64代码
     * @param {string} imageId 图片在Html上的id，用于删除和查找
     */
    createElementImg(spriteNode,imageBase64,imageId,opacity = 1){
   
        var originalNode = spriteNode;

        var bigImg = document.createElement("img");

        var gameDiv = document.getElementById('Cocos2dGameContainer');

        //获取Canvas缩放值
        let scaleX = parseInt(gameDiv.style.width.replace(/px/, '')) / cc.winSize.width;

        let scaleY = parseInt(gameDiv.style.height.replace(/px/, '')) / cc.winSize.height;

        //计算图片在Cocos上的RECT
        var cocosWidth = originalNode.width * originalNode.scaleX;     //图片在Cocos上的宽度
    
        var cocosHeight = originalNode.height * originalNode.scaleY;    //图片在Cocos上的高度

        var leftPointX = originalNode.x - cocosWidth / 2;       //左上角X，因为中心点为（0,0）点

        var leftPointY = originalNode.y + cocosHeight / 2;      //左上角Y，因为中心点为（0,0）点

        var cocosLeft = cc.winSize.width / 2  - Math.abs(leftPointX);

        var cocosTop = cc.winSize.height / 2 - Math.abs(leftPointY);

        //计算在Canvas上的RECT
        var canvasWidth = cocosWidth * scaleX;      //在Canvas上的宽度

        var canvasHeight = cocosHeight * scaleY;    //在Canvas上的高度

        var canvasLeft = cocosLeft * scaleX;        //距离左边距离

        var canvasTop = cocosTop * scaleY;      //距顶部距离

        //赋值
        bigImg.style.position = 'absolute';

        bigImg.width = canvasWidth;

        bigImg.height = canvasHeight;

        bigImg.style.left = canvasLeft + "px";

        bigImg.style.top = canvasTop + "px";

        bigImg.style.opacity = opacity;

        bigImg.src = imageBase64;
 
        bigImg.id = imageId;

        gameDiv.appendChild(bigImg);
    },

    /**
     * 移除Html上的图片，和createElementImg方法配合使用
     * @param {string} imageId 图片在Html上的id，用于删除和查找
     */
    removeElementImg(imageId){

        let gameDiv = document.getElementById('Cocos2dGameContainer');

        let img = document.getElementById(imageId);

        if(img){

            gameDiv.removeChild(img);
        }
    },

    /**
     * 全屏截图
     */
    captureScreenshot(callback) {

        function capture() {

            var canvas = document.getElementById("GameCanvas");

            var base64 = canvas.toDataURL("image/jpeg");

            cc.director.off(cc.Director.EVENT_AFTER_DRAW);

            var frame = this.base64ToSpriteFrame(base64, (frame) => {

                callback(frame, base64);
            });
        }

        cc.director.on(cc.Director.EVENT_AFTER_DRAW, capture.bind(this));
    },

    /**
     * 读取本地照片
     */
    selectImage: function (selectedFunc, thisValue, useOriginalQuality = true) {

        this.selectedHandler = selectedFunc;

        this.thisRef = thisValue;

        this.useOriginalQuality = useOriginalQuality;

        var fileInput = document.getElementById("fileInput");
   
        if (fileInput == null) {
   
            fileInput = document.createElement("input");
           
            fileInput.id = "fileInput";

            fileInput.type = "file";

            fileInput.accept = "image/*";

            fileInput.style.height = "0px";

            fileInput.style.display = "block";

            fileInput.style.overflow = "hidden";
        
            document.body.insertBefore(fileInput, document.body.firstChild);
        
            fileInput.addEventListener('change', this.tmpSelectFile, false);
        }

        setTimeout(function () { fileInput.click() }, 100);
    },

    tmpSelectFile: function (evt) {

        var file = evt.target.files[0];

        var type = file.type;

        if (!type) {

            type = mime[file.name.match(/\.([^\.]+)$/i)[1]];
        }

        var ret = ImageHelper.myCreateObjectURL(file);

        ImageHelper.tmpCreateImage && ImageHelper.tmpCreateImage(ret, file);

        var fileInput = document.getElementById("fileInput");

        fileInput.value = "";
    },

    tmpCreateImage: function (uri, file) {

        var reader = new FileReader();

        function tmpLoad() {

            var re = /^data:base64,/;

            var ret = this.result + '';

            if (re.test(ret)) ret = ret.replace(re, 'data:' + mime[type] + ';base64,');

            //压缩图片
            var image = new Image();

            image.onload = function () {

                var canvas = document.createElement("canvas");

                var t_resultWidth = 1800;

                image.height = image.naturalHeight * t_resultWidth / image.naturalWidth;

                image.width = t_resultWidth;

                var ctx = canvas.getContext("2d");

                ctx.clearRect(0, 0, canvas.width, canvas.height);

                canvas.width = image.width;

                canvas.height = image.height;

                ctx.drawImage(image, 0, 0, image.width, image.height);

                var smallURL = canvas.toDataURL("image/jpeg");

                //console.log(smallURL);

                ImageHelper.getOrientation(file, function (orientation) {

                    //console.log("设备旋转方向：" + orientation);

                    //旋转方向
                    ImageHelper.resetOrientation(smallURL, orientation, function (base64) {

                        ImageHelper.selectedHandler & ImageHelper.selectedHandler(ImageHelper.thisRef, base64, file);
                    });
                });
            }

            image.src = ret;
        }

        reader.onload = tmpLoad;

        reader.readAsDataURL(file);
    },

    myCreateObjectURL: function (blob) {

        if (window.URL != undefined)
            return window['URL']['createObjectURL'](blob);
        else
            return window['webkitURL']['createObjectURL'](blob);
    },

    getImageData: function (file, bytesFunc, thisValue) {

        ImageHelper.bytesHandler = bytesFunc;

        ImageHelper.thisRef = thisValue;

        try { var reader = new FileReader(); }

        catch (err) { console.log("no support FileReader") }

        function tmpLoad() {

            ImageHelper.bytesHandler && ImageHelper.bytesHandler(ImageHelper.thisRef, this.result);
        }

        reader.onload = tmpLoad;

        reader.readAsArrayBuffer(file);
    },

    /**
     * 将Base64转化为SpriteFrame
     */
    base64ToSpriteFrame(base64String, callback) {

        var img = new Image();

        img.src = base64String;

        img.onload = function () {

            var texture = new cc.Texture2D();

            texture.initWithElement(img);

            texture.handleLoadedTexture();

            var newframe = new cc.SpriteFrame(texture);

            callback(newframe);
        }
    },

    /**
     * 数据在传输的时候，需要对其+号和&号进行编码，否则服务器接收造成问题
     * @param {传输的数据} data 
     */
    urlEncode(data) {

        data = data.replace(/\+/g, "%2B");

        data = data.replace(/\&/g, "%26");

        return data;
    },

    /**
     * 获取设备的图片旋转方向
     * @param {Input标签的File} file 
     * @param {返回方向 int} callback 
     */
    getOrientation(file, callback) {

        var reader = new FileReader();

        reader.onload = function (e) {

            var view = new DataView(this.result);

            if (view.getUint16(0, false) != 0xFFD8) return callback(-2);

            var length = view.byteLength, offset = 2;

            while (offset < length) {

                var marker = view.getUint16(offset, false);

                offset += 2;

                if (marker == 0xFFE1) {

                    if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);

                    var little = view.getUint16(offset += 6, false) == 0x4949;

                    offset += view.getUint32(offset + 4, little);

                    var tags = view.getUint16(offset, little);

                    offset += 2;

                    for (var i = 0; i < tags; i++)
                        if (view.getUint16(offset + (i * 12), little) == 0x0112)
                            return callback(view.getUint16(offset + (i * 12) + 8, little));
                }
                else if ((marker & 0xFF00) != 0xFF00) break;
                else offset += view.getUint16(offset, false);
            }

            return callback(-1);
        };

        reader.readAsArrayBuffer(file);
    },

    resetOrientation(srcBase64, srcOrientation, callback) {

        var img = new Image();

        img.onload = function () {

            //console.log("传入的图片W：" + img.width + "  H:" + img.height);

            var width = img.width,
                height = img.height,
                canvas = document.createElement('canvas'),
                ctx = canvas.getContext("2d");

            // 设置旋转后的Canvas长宽
            if ([5, 6, 7, 8].indexOf(srcOrientation) > -1) {
                canvas.width = height;
                canvas.height = width;

                //console.log("Canvas，W：" + canvas.width + "  H:" + canvas.height);
            } else {
                canvas.width = width;
                canvas.height = height;
            }

            switch (srcOrientation) {

                //旋转90度
                case 6:

                    ctx.rotate(Math.PI / 2);

                    ctx.translate(0, -height);

                    ctx.drawImage(img, 0, 0);

                    break;

                //旋转180°
                case 3:

                    ctx.rotate(Math.PI);

                    ctx.translate(-width, -height);

                    ctx.drawImage(img, 0, 0)

                    break;
                //旋转270°
                case 8:

                    ctx.rotate(-Math.PI / 2);       //逆时针旋转90度

                    ctx.translate(-width, 0);

                    ctx.drawImage(img, 0, 0)

                    break;

                default:

                    callback(srcBase64);

                    return;
            }

            // export base64
            callback(canvas.toDataURL("image/jpeg"));
        };

        img.src = srcBase64;
    },
}